import { GetProps, Select } from 'antd'
import type { ICellRendererParams } from '@ag-grid-community/core'

import styles from './styles.module.less'

type TSelectProps = GetProps<typeof Select>

interface ISelectCellRendererProps extends ICellRendererParams<any, any> {
  selectProps?: Omit<TSelectProps, 'value' | 'onChange' | 'disabled'>
}

export const SelectCellRenderer = Object.assign(
  ({ value, node, column, colDef, data, selectProps }: ISelectCellRendererProps) => {
    // 计算是否可编辑（用于禁用控制），兼容 editable 为布尔或函数
    const isEditable = (() => {
      const editable = colDef?.editable as any
      try {
        if (typeof editable === 'function') {
          return !!editable({ data, node, colDef })
        }
        return !!editable
      } catch {
        return !!editable
      }
    })()

    return (
      <Select
        {...selectProps}
        className={styles.SelectCellRenderer}
        disabled={!isEditable}
        value={value as any}
        onChange={val => {
          const colId =
            column?.getColId?.() ?? (typeof (column as any)?.colId === 'string' ? (column as any).colId : undefined)
          if (colId && node) {
            node.setDataValue(colId, val)
          }
        }}
      />
    )
  },
  {
    defineProps: (
      props: Pick<ISelectCellRendererProps, 'selectProps'>,
    ): Pick<ISelectCellRendererProps, 'selectProps'> => props,
  },
)
